﻿using LibNiconico.NiconicoApi.Exceptions;
using LibNiconico.NiconicoApi.Internal.Http;
using LibNiconico.NiconicoApi.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;

namespace LibNiconico.NiconicoApi.Internal
{
    /// <summary>
    /// XML形式で取得するニコニコ情報取得API
    /// </summary>
    internal class NiconicoInfoGetApiXmlImpl:NiconicoInfoGetApiImpl

    {

        internal NiconicoInfoGetApiXmlImpl(Uri url, INiconicoHttpClient api) : base(url, api) { }

        /// <summary>
        /// Getメソッドで非同期に取得
        /// </summary>
        /// <param name="urlAble"></param>
        /// <returns></returns>
        internal async Task<NiconicoHttpResponse< XDocument>> GetAsync(NicoUrlAble urlAble)
        {

            return await getStreamAsyncInternal( GetStreamAsync,urlAble).ConfigureAwait(false);

        }

        /// <summary>
        /// Postメソッドで非同期に取得
        /// </summary>
        /// <param name="postAble"></param>
        /// <returns></returns>
        internal async Task<NiconicoHttpResponse<XDocument>> PostAsync(NicoUrlEncodedPostAble postAble)
        {
            return await getStreamAsyncInternal(PostStreamAsyunc,postAble).ConfigureAwait(false);
        }

        private async Task<NiconicoHttpResponse<XDocument>> getStreamAsyncInternal<T>(Func<T, Task<NiconicoHttpResponse<Stream>>> streamGetFunc, T urlAble)
        {
            try
            {
                var response = await streamGetFunc(urlAble).ConfigureAwait(false);
                using(Stream stream = response.Content){
                     
                    

                    return NiconicoHttpResponse.ConvertContent( XDocument.Load( stream),response);
                }
                
            }
            catch (Exception e)
            {
                throw new NicoApiException(e.Message, e);
            }
        }







    }
}
